package com.coocaa.optimizer.movie.cleaner;

import android.app.ActivityManager;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;

import com.coocaa.optimizer.OptimizerApplication;
import com.coocaa.optimizer.R;
import com.coocaa.optimizer.movie.cleaner.manager.CleanerManager;
import com.coocaa.optimizer.movie.cleaner.manager.CleanerManagerFactory;

public class LowStorageReceiver extends BroadcastReceiver {
    private static final String MOVEPLATFORM_PACKAGE = "com.tianci.movieplatform";

    private static boolean checkIsTopActivity(Context context, String... packageNames) {
        try {
            ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
            ComponentName cn = am.getRunningTasks(1).get(0).topActivity;
            String pkg = cn.getPackageName();
            for (String packageName : packageNames) {
                if (pkg.equals(packageName))
                    return true;
            }
        } catch (Exception e) {
            return false;
        }
        return false;
    }

    private static Thread thread = null;


    @Override
    public void onReceive(final Context context, Intent intent) {
        if (thread == null) {
            thread = new Thread(new Runnable() {
                @Override
                public void run() {
//                    CleanerService.startScanAndAutoClean(context);
                    while (checkIsTopActivity(context, MOVEPLATFORM_PACKAGE))
                        try {
                            Thread.sleep(1000);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    CleanerManager manager = CleanerManagerFactory.factory.create(context);
                    if (manager.canAutoClean()) {
                        manager.cleanNow();
                        OptimizerApplication.toastDebug(context, context.getResources().getString(R.string.auto_clean_now_success));
                    }
                    thread = null;
                }
            });
            thread.start();
        }
    }
}
